package com.online.onlineshop.controllers;

import com.alibaba.fastjson.JSONObject;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author zihao.wang1
 * @date 2022/5/5
 */
@RestController
@RequestMapping("/imgUpload")
public class imgUploadController {

    @RequestMapping("upload")
    public JSONObject upload(@RequestParam(value = "file") MultipartFile file) {
        String newFileName = file.getOriginalFilename();
        if (newFileName != null) {
            newFileName = newFileName.substring(0, newFileName.indexOf("."));
        }
        String imgPath = "D:\\grade_project\\yinong-shop\\src\\main\\resources\\static\\images\\portal\\";
        //文件夹不存在则创建，存在则不创建
        File file1 = new File(imgPath + newFileName);
        if (!file1.mkdir()) {
            JSONObject jo = new JSONObject();
            jo.put("code", 1);
            jo.put("msg", "图片已上传，无需重复上传");
            jo.put("src", "/images/portal/" + newFileName + "/");
            return jo;
        }

        for (int i = 0; i <= 5; i++) {
            File targetFile;
            try {
                if (i > 0) {
                    //提取复制母本
                    File baseImgFile = new File(imgPath + newFileName + File.separator + "collect.png");
                    //按展示格式复制图片
                    targetFile = new File(imgPath + newFileName + File.separator + i + ".jpg");
                    MultipartFile cMultiFile1 = new MockMultipartFile("file", file.getName(), null, new FileInputStream(baseImgFile));
                    cMultiFile1.transferTo(targetFile.getAbsoluteFile());

                    targetFile = new File(imgPath + newFileName + File.separator + i + "_big.png");
                    MultipartFile cMultiFile2 = new MockMultipartFile("file", file.getName(), null, new FileInputStream(baseImgFile));
                    cMultiFile2.transferTo(targetFile.getAbsoluteFile());
                } else {
                    targetFile = new File(imgPath + newFileName + File.separator + "collect.png");
                    file.transferTo(targetFile.getAbsoluteFile());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        JSONObject jo = new JSONObject();
        jo.put("code", 0);
        jo.put("msg", "");
        jo.put("src", "/images/portal/" + newFileName + "/");
        return jo;
    }
}
